package com.nifostasky.comic.common.exception;

import com.nifostasky.comic.exceptions.BusinessException;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 捕获filter中的自定义异常
 */
@Component
public class ExceptionFilter implements Filter{

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        try {
            filterChain.doFilter(httpRequest, httpResponse);
        } catch (BusinessException e) {
            // 异常捕获，加入到request域中
            httpRequest.setAttribute("filterException", e);
            //将异常分发到 /exception控制器
            httpRequest.getRequestDispatcher("/exception/throwBusinessException").forward(httpRequest, httpResponse);
        }
    }
}
